package com.lzy.cloud.goods.facade;

import com.lzy.cloud.goods.constant.GoodsParam;
import com.lzy.cloud.goods.dtos.CarCalendarDto;
import com.lzy.cloud.goods.dtos.HourCalendarDto;
import com.lzy.cloud.goods.service.HourCalendarService;
import com.lzy.cloud.goods.service.carRent.CarCalendarService;
import com.lzy.cloud.goods.utils.CommonUtil;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.utils.DateUtil;
import com.lzy.framework.core.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class CarCalendarFacade {

    @Autowired
    CarCalendarService carCalendarService;

    @Autowired
    HourCalendarService hourCalendarService;

    /**
     * 批量设置单个房车档期区间（区间内的区间）
     *
     * @param carCalendarDto
     * @return
     */
    public Boolean updateWeekdays(CarCalendarDto carCalendarDto){
        Ensure.that(carCalendarDto).isNotNull("");
        if(StringUtil.isNotEmpty(carCalendarDto.getWeekStr())){
            String[] weekList = carCalendarDto.getWeekStr().split(",");
            List dayList = new ArrayList();
            for (String week:weekList) {
                if(StringUtil.isNotEmpty(week)){
                    dayList.add(Integer.valueOf(week));
                }
            }
            List<Integer> weekdayList = new ArrayList<>();
            String weekdays = "";
            if(dayList.contains(0)){
//                weekdays = "1,2,3,4,5,6,7,";
                for (int i = 1;i <= 7;i++) {
                    weekdayList.add(i);
                }
            }else{
                for (int i = 0;i<dayList.size();i++){
                    weekdayList.addAll(dayList);
                }
            }
            //获取两个日期的天数
            Integer daysBetween = 0;
            String afterDay = carCalendarDto.getStartDate();
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                daysBetween = DateUtil.daysBetween(carCalendarDto.getStartDate(),carCalendarDto.getEndDate());
                for(int m = 0;m <= daysBetween;m ++){
                    Date beg = sdf.parse(afterDay);
                    //根据日期获取是周几
                    String n = getWeekOfDate(beg);
                    //判断n是否在weekdays中
                    if(weekdayList.contains(Integer.valueOf(n))){
                        //如果包含，档期存在的覆盖，不存在的新增
                        CarCalendarDto ccDto = new CarCalendarDto();
                        ccDto.setDate(afterDay);
                        ccDto.setCarId(carCalendarDto.getCarId());
                        CarCalendarDto carCalendarDto1 = carCalendarService.selectByCarIdAndDate(ccDto);
                        if(carCalendarDto1 != null){
                            carCalendarService.delById(carCalendarDto1.getId());
                        }
                        CarCalendarDto calendarDto = new CarCalendarDto();
                        calendarDto.setCarId(carCalendarDto.getCarId());
                        calendarDto.setDate(afterDay);
                        calendarDto.setHoliday(isHoliday(n));
                        calendarDto.setWeekday(Integer.valueOf(n));
                        calendarDto.setType(carCalendarDto.getType());
                        calendarDto.setPrice(carCalendarDto.getPrice());
                        carCalendarService.insertSelective(calendarDto);
                    }
                    afterDay = getAfterDayByDate(afterDay);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return true;
        }
        return false;
    }

    /**
     * 判断这个周几是否为节假日（周五，周六，周日为节假日）
     * @param weekday
     * @return
     */
    public Integer isHoliday(String weekday){
        Integer n = Integer.valueOf(weekday);
        if(n == 5 || n == 6 || n == 7){
            return 1;
        }
        return 0;
    }

    /**
     * 根据时间得到星期几
     *
     * @param date
     * @return
     * @Description: TODO
     * @author lyz
     * @date 2017年5月16日  下午2:03:17
     */
    public String getWeekOfDate(Date date) {
        String[] weekOfDays = {"7", "1", "2", "3", "4", "5", "6"};
        Calendar calendar = Calendar.getInstance();
        if (date != null) {
            calendar.setTime(date);
        }
        int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return weekOfDays[w];
    }

    public String getAfterDayByDate(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();//获取日历实例
        try {
            calendar.setTime(sdf.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        calendar.add(Calendar.DAY_OF_MONTH, 1);  //设置为后一天
        String afterDay = sdf.format(calendar.getTime());//获得后一天
        return afterDay;
    }

    public Boolean updateByCarIdAndDates(CarCalendarDto carCalendarDto){
        Integer countDay = 0;
        try {
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date beg = sdf.parse(carCalendarDto.getStartDate());
            Date end = sdf.parse(carCalendarDto.getEndDate());
            //计算租赁的天数
            countDay = (int) ((end.getTime() - beg.getTime()) / 86400000) + 1;
            //保存档期
            //  calendarService.delScheduleByCarId(request.getCarId());
            for (int j = 0; j < countDay; j++) {
                cal.setTime(new Date(beg.getTime()));
                cal.add(Calendar.DATE, j);
                carCalendarDto.setWeekday(Integer.parseInt(getWeekOfDate(cal.getTime())));
                carCalendarDto.setDate(sdf.format(cal.getTime()));
                carCalendarDto.setPrice(carCalendarDto.getPrice());//默认价格
                CarCalendarDto caDto = carCalendarService.findByCarId(carCalendarDto);
                if (caDto != null && caDto.getType() != 4) {
                    carCalendarService.updateCarCalendar(carCalendarDto);
                } else if(caDto == null){
                    carCalendarService.insertSelective(carCalendarDto);
                }
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return countDay>0?true:false;
    }

    /**
     * 查询档期列表
     * @param carCalendarDto
     * @return
     */
    public List<CarCalendarDto> selectOneMonthList(CarCalendarDto carCalendarDto){
        List<CarCalendarDto> carCalendarDtoList = carCalendarService.selectOneMonthList(carCalendarDto);
        HourCalendarDto hourCalendarDto = new HourCalendarDto();
        hourCalendarDto.setSourceType(1);
        hourCalendarDto.setSourceId(carCalendarDto.getCarId());
        if(carCalendarDtoList != null && carCalendarDtoList.size() > 0){
            for (CarCalendarDto ccDto:carCalendarDtoList) {
                hourCalendarDto.setDate(ccDto.getDate());
                List<HourCalendarDto> hourCalendarDtoList = hourCalendarService.selectList(hourCalendarDto);
                if(hourCalendarDtoList != null && hourCalendarDtoList.size() > 0){
                    ccDto.setHourCalendarList(hourCalendarDtoList);
                }
            }
        }
        return carCalendarDtoList;
    }

    /**
     * 获取单个房车的单个档期(一个日期)详情
     *
     * @param carCalendarDto
     * @return
     */
    public CarCalendarDto selectByCarIdAndDate(CarCalendarDto carCalendarDto){
        CarCalendarDto calendarDto = carCalendarService.selectByCarIdAndDate(carCalendarDto);
        if(calendarDto != null){
            HourCalendarDto hcDto = new HourCalendarDto();
            hcDto.setSourceType(1);
            hcDto.setSourceId(carCalendarDto.getCarId());
            hcDto.setDate(carCalendarDto.getDate());
            List<HourCalendarDto> hourCalendarDtoList = hourCalendarService.selectList(hcDto);
            if(hourCalendarDtoList != null){
                calendarDto.setHourCalendarList(hourCalendarDtoList);
            }
        }
        return calendarDto;
    }

    /**
     * 单个房车单个档期(一个日期)更新或新增
     *
     * @param carCalendarDto
     * @return
     */
    public Boolean updateByCarIdAndOneDate(CarCalendarDto carCalendarDto){
        //更新档期主表
        carCalendarService.updateByCarIdAndOneDate(carCalendarDto);
        if (carCalendarDto.getType() != null && carCalendarDto.getType() != 4 && carCalendarDto.getType() != 5) {
            //删除小时档期表type为非订单的数据
            HourCalendarDto hourCalendarDto = new HourCalendarDto();
            hourCalendarDto.setSourceType(1);
            hourCalendarDto.setSourceId(carCalendarDto.getCarId());
            hourCalendarDto.setDate(carCalendarDto.getDate());
            hourCalendarService.deleteByNoOrderType(hourCalendarDto);
            //新增type为非订单的数据
            HourCalendarDto hcDto = new HourCalendarDto();
            hcDto.setDate(carCalendarDto.getDate());
            hcDto.setStartTime(carCalendarDto.getStartTime());
            hcDto.setEndTime(carCalendarDto.getEndTime());
            hcDto.setType(carCalendarDto.getType());
            hcDto.setSourceId(carCalendarDto.getCarId());
            hcDto.setSourceType(1);
            hourCalendarService.addHourCalendar(hcDto);
        }
        return true;
    }

    /**
     * 查询有没有空档期，有就占用
     *
     * @param carCalendarDto
     * @return
     */
    public Boolean findEmptyCalendarAndOccupy(CarCalendarDto carCalendarDto){
        // 开始时间
        String startTime = carCalendarDto.getStartDate();
        // 结束时间
        String endTime = carCalendarDto.getEndDate();
        if (StringUtil.isEmpty(startTime) || StringUtil.isEmpty(endTime)) {
            return false;
        }
        // 开始日期
        String startDate = StringUtil.substring(startTime, 0, 10);
        // 结束日期
        String endDate = StringUtil.substring(endTime, 0, 10);

        if (startDate.equals(endDate)) { // 开始日期和结束日期在同一天
            // 查小时档期
            HourCalendarDto searchDto = new HourCalendarDto();
            searchDto.setDate(startDate);
            searchDto.setSourceId(carCalendarDto.getCarId());
            searchDto.setSourceType(GoodsParam.GOODS_HOUR_CALENDAR_SOURCE_TYPE_CAR_RENT);
            List<HourCalendarDto> hourCalendarDtoList = hourCalendarService.selectList(searchDto);
            for (int i = 0; i < hourCalendarDtoList.size(); i++) {
                HourCalendarDto hourCalendarDto = hourCalendarDtoList.get(i);
                // 开始时间<=小时档期的结束时间 &&　结束时间>=小时档期的开始时间
                if (hourCalendarDto != null
                        && hourCalendarDto.getType() != GoodsParam.GOODS_CAR_CALENDAR_TYPE_RENT
                        && isLte(startTime, hourCalendarDto.getDate() + " " + hourCalendarDto.getEndTime() + ":00")
                        && isLte(hourCalendarDto.getDate() + " " + hourCalendarDto.getStartTime() + ":00", endTime)) {
                    return false;
                }
            }

            // 查档期
            if (hourCalendarDtoList.size() == 0) {
                CarCalendarDto searchDto2 = new CarCalendarDto();
                searchDto2.setCarId(carCalendarDto.getCarId());
                searchDto2.setDate(startDate);
                CarCalendarDto carCalendarDto2 = carCalendarService.findByCarId(searchDto2);
                if (carCalendarDto2 == null || carCalendarDto2.getType() != GoodsParam.GOODS_CAR_CALENDAR_TYPE_RENT) {
                    return false;
                }
            }

            // 占用档期
            HourCalendarDto hourCalendarDto = new HourCalendarDto();
            hourCalendarDto.setSourceId(carCalendarDto.getCarId());
            hourCalendarDto.setSourceType(GoodsParam.GOODS_HOUR_CALENDAR_SOURCE_TYPE_CAR_RENT);
            hourCalendarDto.setDate(startDate);
            hourCalendarDto.setStartTime(StringUtil.substring(startTime, 11, 16));
            hourCalendarDto.setEndTime(StringUtil.substring(endTime, 11, 16));
            hourCalendarDto.setType(GoodsParam.GOODS_CAR_CALENDAR_TYPE_RENT);
            boolean result = hourCalendarService.addHourCalendar(hourCalendarDto);

            return result;
        } else { // 开始时间和结束时间不在同一天
            // 间隔天数
            long days = CommonUtil.getDistanceDays(startDate, endDate);

            // 1.开始时间
            // 小时档期
            HourCalendarDto searchDto = new HourCalendarDto();
            searchDto.setDate(startDate);
            searchDto.setSourceId(carCalendarDto.getCarId());
            searchDto.setSourceType(GoodsParam.GOODS_HOUR_CALENDAR_SOURCE_TYPE_CAR_RENT);
            List<HourCalendarDto> hourCalendarDtoList = hourCalendarService.selectList(searchDto);
            for (int i = 0; i < hourCalendarDtoList.size(); i++) {
                HourCalendarDto hourCalendarDto = hourCalendarDtoList.get(i);
                // 开始时间<=小时档期的结束时间
                if (hourCalendarDto != null && hourCalendarDto.getType() != GoodsParam.GOODS_CAR_CALENDAR_TYPE_RENT &&
                        isLte(startTime, hourCalendarDto.getDate() + " " + hourCalendarDto.getEndTime() + ":00")) {
                    return false;
                }
            }
            // 档期
            if (hourCalendarDtoList.size() == 0) {
                CarCalendarDto searchDto2 = new CarCalendarDto();
                searchDto2.setCarId(carCalendarDto.getCarId());
                searchDto2.setDate(startDate);
                CarCalendarDto carCalendarDto2 = carCalendarService.findByCarId(searchDto2);
                if (carCalendarDto2 == null || carCalendarDto2.getType() != GoodsParam.GOODS_CAR_CALENDAR_TYPE_RENT) {
                    return false;
                }
            }

            // 2.有间隔整天
            if (days > 2) {
                String startDate1 = startDate;
                for (int i = 0; i < days - 2; i++) {
                    // 小时档期
                    startDate1 = CommonUtil.addOneDayForDate(startDate1);
                    searchDto = new HourCalendarDto();
                    searchDto.setDate(startDate1);
                    searchDto.setSourceId(carCalendarDto.getCarId());
                    searchDto.setSourceType(GoodsParam.GOODS_HOUR_CALENDAR_SOURCE_TYPE_CAR_RENT);
                    hourCalendarDtoList = hourCalendarService.selectList(searchDto);
                    for (int j = 0; j < hourCalendarDtoList.size(); j++) {
                        HourCalendarDto hourCalendarDto = hourCalendarDtoList.get(j);
                        // 有占用的档期
                        if (hourCalendarDto != null && hourCalendarDto.getType() != GoodsParam.GOODS_CAR_CALENDAR_TYPE_RENT) {
                            return false;
                        }
                    }
                    // 档期
                    CarCalendarDto searchDto2 = new CarCalendarDto();
                    searchDto2.setCarId(carCalendarDto.getCarId());
                    searchDto2.setDate(startDate1);
                    CarCalendarDto carCalendarDto2 = carCalendarService.findByCarId(searchDto2);
                    if (carCalendarDto2 == null || carCalendarDto2.getType() != GoodsParam.GOODS_CAR_CALENDAR_TYPE_RENT) {
                        return false;
                    }
                }
            }

            // 3.结束时间
            // 小时档期
            searchDto = new HourCalendarDto();
            searchDto.setDate(endDate);
            searchDto.setSourceId(carCalendarDto.getCarId());
            searchDto.setSourceType(GoodsParam.GOODS_HOUR_CALENDAR_SOURCE_TYPE_CAR_RENT);
            hourCalendarDtoList = hourCalendarService.selectList(searchDto);
            for (int i = 0; i < hourCalendarDtoList.size(); i++) {
                HourCalendarDto hourCalendarDto = hourCalendarDtoList.get(i);
                // 结束时间>=小时档期的开始时间
                if (hourCalendarDto != null && hourCalendarDto.getType() != GoodsParam.GOODS_CAR_CALENDAR_TYPE_RENT &&
                        isLte( hourCalendarDto.getDate() + " " + hourCalendarDto.getStartTime() + ":00", endTime)) {
                    return false;
                }
            }
            // 档期
            if (hourCalendarDtoList.size() == 0) {
                CarCalendarDto searchDto2 = new CarCalendarDto();
                searchDto2.setCarId(carCalendarDto.getCarId());
                searchDto2.setDate(endDate);
                CarCalendarDto carCalendarDto2 = carCalendarService.findByCarId(searchDto2);
                if (carCalendarDto2 == null || carCalendarDto2.getType() != GoodsParam.GOODS_CAR_CALENDAR_TYPE_RENT) {
                    return false;
                }
            }

            // 4.TODO 占用档期
            HourCalendarDto hourCalendarDto = new HourCalendarDto();
            hourCalendarDto.setSourceId(carCalendarDto.getCarId());
            hourCalendarDto.setSourceType(GoodsParam.GOODS_HOUR_CALENDAR_SOURCE_TYPE_CAR_RENT);
            hourCalendarDto.setDate(startDate);
            hourCalendarDto.setStartTime(StringUtil.substring(startTime, 11, 16));
            hourCalendarDto.setEndTime("24:00");
            hourCalendarDto.setType(GoodsParam.GOODS_CAR_CALENDAR_TYPE_ORDER);
            Ensure.that(hourCalendarService.addHourCalendar(hourCalendarDto)).isTrue("00100001");
            if (days > 2) {
                String startDate1 = startDate;
                for (int i = 0; i < days - 2; i++) {
                    startDate1 = CommonUtil.addOneDayForDate(startDate1);
                    hourCalendarDto = new HourCalendarDto();
                    hourCalendarDto.setSourceId(carCalendarDto.getCarId());
                    hourCalendarDto.setSourceType(GoodsParam.GOODS_HOUR_CALENDAR_SOURCE_TYPE_CAR_RENT);
                    hourCalendarDto.setDate(startDate1);
                    hourCalendarDto.setStartTime("00:00");
                    hourCalendarDto.setEndTime("24:00");
                    hourCalendarDto.setType(GoodsParam.GOODS_CAR_CALENDAR_TYPE_ORDER);
                    Ensure.that(hourCalendarService.addHourCalendar(hourCalendarDto)).isTrue("00100001");
                }
            }
            hourCalendarDto = new HourCalendarDto();
            hourCalendarDto.setSourceId(carCalendarDto.getCarId());
            hourCalendarDto.setSourceType(GoodsParam.GOODS_HOUR_CALENDAR_SOURCE_TYPE_CAR_RENT);
            hourCalendarDto.setDate(endDate);
            hourCalendarDto.setStartTime("00:00");
            hourCalendarDto.setEndTime(StringUtil.substring(endTime, 11, 16));
            hourCalendarDto.setType(GoodsParam.GOODS_CAR_CALENDAR_TYPE_ORDER);
            Ensure.that(hourCalendarService.addHourCalendar(hourCalendarDto)).isTrue("00100001");
            return true;
        }
    }

    /**
     * 时间小于等于
     * @param time1
     * @param time2
     * @return
     */
    private static boolean isLte(String time1, String time2) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            long t1=sdf.parse(time1).getTime();
            long t2=sdf.parse(time2).getTime();
            return t1 <= t2;
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 释放档期
     * @param carCalendarDto
     * @return
     */
    public boolean releaseCalendar(CarCalendarDto carCalendarDto) {
        // 开始时间
        String startTime = carCalendarDto.getStartDate();
        // 结束时间
        String endTime = carCalendarDto.getEndDate();
        if (StringUtil.isEmpty(startTime) || StringUtil.isEmpty(endTime)) {
            return false;
        }
        // 开始日期
        String startDate = StringUtil.substring(startTime, 0, 10);
        // 结束日期
        String endDate = StringUtil.substring(endTime, 0, 10);

        if (startDate.equals(endDate)) { // 开始日期和结束日期在同一天
            HourCalendarDto hourCalendarDto = new HourCalendarDto();
            hourCalendarDto.setSourceId(carCalendarDto.getCarId());
            hourCalendarDto.setSourceType(GoodsParam.GOODS_HOUR_CALENDAR_SOURCE_TYPE_CAR_RENT);
            hourCalendarDto.setDate(startDate);
            hourCalendarDto.setStartTime(StringUtil.substring(startTime, 11, 16));
            hourCalendarDto.setEndTime(StringUtil.substring(endTime, 11, 16));
            hourCalendarDto.setType(GoodsParam.GOODS_CAR_CALENDAR_TYPE_RENT);
            List<HourCalendarDto> list = hourCalendarService.selectList(hourCalendarDto);
            if (list != null && list.size() > 0) {
                Ensure.that(hourCalendarService.delete(list.get(0).getId())).isTrue("00100002");
            }
        } else {
            // 间隔天数
            long days = CommonUtil.getDistanceDays(startDate, endDate);

            HourCalendarDto hourCalendarDto = new HourCalendarDto();
            hourCalendarDto.setSourceId(carCalendarDto.getCarId());
            hourCalendarDto.setSourceType(GoodsParam.GOODS_HOUR_CALENDAR_SOURCE_TYPE_CAR_RENT);
            hourCalendarDto.setDate(startDate);
            hourCalendarDto.setStartTime(StringUtil.substring(startTime, 11, 16));
            hourCalendarDto.setEndTime("24:00");
            hourCalendarDto.setType(GoodsParam.GOODS_CAR_CALENDAR_TYPE_RENT);
            List<HourCalendarDto> list = hourCalendarService.selectList(hourCalendarDto);
            if (list != null && list.size() > 0) {
                Ensure.that(hourCalendarService.delete(list.get(0).getId())).isTrue("00100002");
            }
            if (days > 2) {
                String startDate1 = startDate;
                for (int i = 0; i < days - 2; i++) {
                    startDate1 = CommonUtil.addOneDayForDate(startDate1);
                    hourCalendarDto = new HourCalendarDto();
                    hourCalendarDto.setSourceId(carCalendarDto.getCarId());
                    hourCalendarDto.setSourceType(GoodsParam.GOODS_HOUR_CALENDAR_SOURCE_TYPE_CAR_RENT);
                    hourCalendarDto.setDate(startDate1);
                    hourCalendarDto.setStartTime("00:00");
                    hourCalendarDto.setEndTime("24:00");
                    hourCalendarDto.setType(GoodsParam.GOODS_CAR_CALENDAR_TYPE_RENT);
                    list = hourCalendarService.selectList(hourCalendarDto);
                    if (list != null && list.size() > 0) {
                        Ensure.that(hourCalendarService.delete(list.get(0).getId())).isTrue("00100002");
                    }
                }
            }
            hourCalendarDto = new HourCalendarDto();
            hourCalendarDto.setSourceId(carCalendarDto.getCarId());
            hourCalendarDto.setSourceType(GoodsParam.GOODS_HOUR_CALENDAR_SOURCE_TYPE_CAR_RENT);
            hourCalendarDto.setDate(endDate);
            hourCalendarDto.setStartTime("00:00");
            hourCalendarDto.setEndTime(StringUtil.substring(endTime, 11, 16));
            hourCalendarDto.setType(GoodsParam.GOODS_CAR_CALENDAR_TYPE_RENT);
            hourCalendarService.addHourCalendar(hourCalendarDto);
            list = hourCalendarService.selectList(hourCalendarDto);
            if (list != null && list.size() > 0) {
                Ensure.that(hourCalendarService.delete(list.get(0).getId())).isTrue("00100002");
            }
        }
        return true;
    }
}
